<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"
import { useUserStore } from "@/stores/index"
import { Key, Loading, Lock, Picture, User } from "@element-plus/icons-vue"
import { useRouter } from "vue-router";
import { computed, reactive, ref } from "vue";
import Owl from "@/views/login/components/Owl.vue"
import { useFocus } from "@/views/login/composables/useFocus"
import { getTimeState } from "@/utils/utils";
import { useKeepAliveStore,useTabsStore } from "@/stores/index";

const router = useRouter()

const userStore = useUserStore()
const TabsStore = useTabsStore()
const KeepAliveStore = useKeepAliveStore()

const { isFocus, handleBlur, handleFocus } = useFocus()

/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)

/** 登录按钮 Loading */
const loading = ref(false)

/** 验证码图片 URL */
const codeUrl = ref("")

/** 登录表单数据 */
const loginFormData: any = reactive({
  username: "admin",
  password: "111111",
  // code: ""
})


/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 1, max: 6, message: "长度在 1 到 6 个字符", trigger: "blur" }

  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ],
  // code: [
  //   { required: true, message: "请输入验证码", trigger: "blur" },
  //   {validator:code,trigger: "blur" }
  // ]
}

const messageTime=computed(()=>getTimeState())

/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    loading.value = true
    userStore.login(loginFormData).then((res) => {
      // console.log(res);
      // console.log(messageTime.value);
      ElNotification({
        title: `${messageTime.value}`,
        message: "欢迎回来",
        type: 'success',
      })
      TabsStore.setTabs([])
      KeepAliveStore.setKeepAliveName()
      router.push("/")
    }).catch((err) => {
      // createCode() //刷星验证码
      ElMessage.error(err.message)
      loginFormData.password = ""
    }).finally(() => {
      loading.value = false
    })
  })
}

/** 创建验证码 */
function createCode() {
  // 清空已输入的验证码
  loginFormData.code = ""
  // 清空验证图片
  codeUrl.value = ""
  // 获取验证码图片
  // getLoginCodeApi().then((res) => {
  //   codeUrl.value = res.data
  // })
}

// 初始化验证码
createCode()

</script>

<template>
  <div class="login-container">
    <!-- <ThemeSwitch v-if="settingsStore.showThemeSwitch" class="theme-switch" /> -->
    <Owl :close-eyes="isFocus" />
    <div class="login-card">
      <div class="title">
        <img src="../../assets/logo.png">
      </div>
      <div class="content">
        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input v-model.trim="loginFormData.username" placeholder="用户名" type="text" tabindex="1"
              :prefix-icon="User" size="large" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="loginFormData.password" placeholder="密码" type="password" tabindex="2"
              :prefix-icon="Lock" size="large" show-password @blur="handleBlur" @focus="handleFocus" />
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model.trim="loginFormData.codes" placeholder="验证码" type="text" tabindex="3" :prefix-icon="Key"
              maxlength="7" size="large" @blur="handleBlur" @focus="handleFocus">
              <template #append>
                <el-image :src="codeUrl" draggable="false" @click="createCode">
                  <template #placeholder>
                    <el-icon> <Picture /> </el-icon>
                  </template>
                  <template #error>
                    <el-icon><Loading /></el-icon>
                  </template>
                </el-image>
              </template>
            </el-input>
          </el-form-item>
          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleLogin">
            登 录
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .login-card {
    width: 480px;
    max-width: 90%;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: var(--el-bg-color);
    overflow: hidden;

    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 130px;

      img {
        height: 100%;
      }
    }

    .content {
      padding: 20px 50px 50px 50px;

      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;

        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }

      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}
</style>
